<template>
  <div class="admin-home">
    <!-- 左侧竖向导航（ERP 首页风格） -->
    <aside class="left-nav">
      <div class="logo">B3</div>
      <div class="nav-items">
        <button
          v-for="it in navItems"
          :key="it.key"
          class="nav-item"
          :class="{ active: activeKey === it.key }"
          @click="onNavClick(it)"
          :title="it.label"
        >
          <component :is="it.icon" class="icon" />
          <span class="label">{{ it.label }}</span>
        </button>
      </div>
    </aside>

    <!-- 右侧内容占位 -->
    <main class="content">
      <div class="toolbar">
        <div class="title">ERP 首页</div>
        <div class="actions">
          <el-button size="small" type="primary" @click="openPanel('search')">搜索</el-button>
          <el-button size="small" @click="openPanel('favorites')">收藏</el-button>
        </div>
      </div>
      <div class="placeholder">
        <div class="big">欢迎使用 ERP 管理系统</div>
        <div class="sub">点击左侧图标进行导航，或打开左侧抽屉搜索/收藏</div>
      </div>
    </main>

    <!-- 左侧抽屉：搜索 -->
    <transition name="slide-in">
      <section v-if="panelVisible && panelType==='search'" class="side-panel">
        <div class="panel-header">
          <div class="title">功能搜索</div>
          <button class="close-btn" @click="closePanel">×</button>
        </div>
        <div class="panel-body">
          <div class="search-box">
            <el-input
              v-model="searchText"
              placeholder="输入功能名称/路径 按回车跳转"
              clearable
              @keyup.enter.native="doSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-button type="primary" @click="doSearch">查询</el-button>
          </div>

          <div class="section">
            <div class="section-head">
              <div class="sec-title">搜索结果</div>
              <span class="muted" v-if="searchResults.length">共 {{ searchResults.length }} 项</span>
            </div>
            <div class="results" v-if="searchResults.length">
              <div class="result-item" v-for="it in searchResults" :key="it.path" @click="go(it.path)">
                <div class="r-main">
                  <div class="r-title">{{ it.title }}</div>
                  <div class="r-path">{{ it.path }}</div>
                </div>
                <el-button size="small" @click.stop="go(it.path)">进入</el-button>
              </div>
            </div>
            <div v-else class="empty">输入关键词查找功能模块</div>
          </div>

          <div class="section">
            <div class="section-head">
              <div class="sec-title">搜索记录</div>
              <button class="link" @click="clearHistory" v-if="recentSearches.length">清空搜索记录</button>
            </div>
            <div class="tags" v-if="recentSearches.length">
              <span class="tag" v-for="kw in recentSearches" :key="kw" @click="applyKeyword(kw)">{{ kw }}</span>
            </div>
            <div v-else class="empty">暂无搜索记录</div>
          </div>
        </div>
      </section>
    </transition>

    <!-- 左侧抽屉：收藏 -->
    <transition name="slide-in">
      <section v-if="panelVisible && panelType==='favorites'" class="side-panel">
        <div class="panel-header">
          <div class="title">导航收藏夹 <span class="muted">{{ favoriteCount }} 项收藏</span></div>
          <button class="close-btn" @click="closePanel">×</button>
        </div>
        <div class="panel-body">
          <div class="fav-groups">
            <div class="fav-group" v-for="group in favoriteGroups" :key="group.name">
              <div class="group-title">{{ group.name }}</div>
              <div class="group-items">
                <div class="fav-item" v-for="item in group.items" :key="item.path">
                  <span class="fav-name" @click="go(item.path)">{{ item.title }}</span>
                  <button class="star-btn" :class="{ on: isFav(item.path) }" @click="toggleFav(item.path)">
                    <el-icon><component :is="isFav(item.path) ? StarFilled : Star" /></el-icon>
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>
    </transition>

    <!-- 左侧抽屉：档案（与收藏一致，靠左导航右侧弹出） -->
    <transition name="slide-in">
      <section v-if="panelVisible && panelType==='archives'" class="side-panel">
        <div class="panel-header">
          <div class="title">档案导航</div>
          <button class="close-btn" @click="closePanel">×</button>
        </div>
        <div class="panel-body">
          <div class="fav-groups">
            <div class="fav-group" v-for="group in archiveGroupsRef" :key="group.name">
              <div class="group-title">{{ group.name }}</div>
              <div class="group-items">
                <div class="fav-item" v-for="item in group.items" :key="item.path">
                  <span class="fav-name" @click="go(item.path)">{{ item.title }}</span>
                  <button class="star-btn" :class="{ on: isFav(item.path) }" @click="toggleFav(item.path)">
                    <el-icon><component :is="isFav(item.path) ? StarFilled : Star" /></el-icon>
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>
    </transition>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { Search, Star, StarFilled, HomeFilled, Collection, Goods, ShoppingCartFull, Share, Box, Wallet, OfficeBuilding, User, DataAnalysis, Setting, Key } from '@element-plus/icons-vue'

const router = useRouter()

// 左侧导航
const navItems = [
  { key: 'search', label: '搜索', icon: Search, type: 'panel' },
  { key: 'favorites', label: '收藏', icon: Star, type: 'panel' },
  { key: 'home', label: '首页', icon: HomeFilled, path: '/mall/dashboard' },
  { key: 'archives', label: '档案', icon: Collection, type: 'panel', children: [
    {
      name: '系统档案',
      items: [
        { title: '商品档案', path: '/mall/catalog' },
        { title: '颜色管理', path: '/mall/colors' },
        { title: '尺码管理', path: '/mall/sizes' },
        { title: '吊牌/条码', path: '/mall/tags' },
        { title: '设备与打印', path: '/mall/devices' },
      ]
    },
    {
      name: '仓库与库存属性',
      items: [
        { title: '库存查询', path: '/mall/inventory' },
        { title: '盘点任务', path: '/mall/stocktake' },
        { title: '损益处理', path: '/mall/loss' },
        { title: '调拨单', path: '/mall/transfers' },
        { title: '补货单', path: '/mall/replenishments' },
      ]
    },
    {
      name: '供应与采购',
      items: [
        { title: '供应商', path: '/mall/suppliers' },
        { title: '采购单', path: '/mall/purchase' },
        { title: '退货单', path: '/mall/returns' },
      ]
    },
    {
      name: '客户档案',
      items: [
        { title: '会员中心', path: '/mall/members' },
        { title: '会员等级', path: '/mall/member-tiers' },
        { title: '积分规则', path: '/mall/points' },
        { title: '储值管理', path: '/mall/stored-value' },
      ]
    },
    {
      name: '门店与权限',
      items: [
        { title: '门店资料', path: '/mall/stores' },
        { title: '收银点', path: '/mall/registers' },
        { title: '员工与权限', path: '/mall/users' },
      ]
    },
    {
      name: '报表与分析',
      items: [
        { title: '销售分析', path: '/mall/report-sales' },
        { title: '款色尺码结构', path: '/mall/report-matrix' },
        { title: '季节动销', path: '/mall/report-season' },
        { title: '库存老化', path: '/mall/report-aging' },
        { title: '店员绩效', path: '/mall/report-staff' },
      ]
    },
  ] },
  { key: 'products', label: '商品', icon: Goods, path: '/mall/catalog' },
  { key: 'purchase', label: '采购', icon: ShoppingCartFull, path: '/mall/purchase' },
  { key: 'distribution', label: '分销', icon: Share, path: '/mall/transfers' },
  { key: 'inventory', label: '库存', icon: Box, path: '/mall/inventory' },
  { key: 'finance', label: '财务', icon: Wallet, path: '/mall/settlement' },
  { key: 'stores', label: '门店', icon: OfficeBuilding, path: '/mall/stores' },
  { key: 'members', label: '会员', icon: User, path: '/mall/members' },
  { key: 'reports', label: '报表', icon: DataAnalysis, path: '/mall/report-sales' },
  { key: 'system', label: '系统', icon: Setting, path: '/mall/settings' },
  { key: 'auth', label: '授权', icon: Key, path: '/mall/users' },
]

const activeKey = ref('home')

// 抽屉
const panelVisible = ref(false)
const panelType = ref('search')
const openPanel = (type) => { panelType.value = type; panelVisible.value = true }
const closePanel = () => { panelVisible.value = false }
const onNavClick = (it) => {
  if (it.type === 'panel') { 
    // 如果是档案，使用 children 作为当前抽屉内容数据源
    if (it.key === 'archives' && Array.isArray(it.children)) {
      archiveGroupsRef.value = it.children
    } else {
      archiveGroupsRef.value = archiveGroups
    }
    openPanel(it.key); 
    return 
  }
  activeKey.value = it.key
  router.push(it.path)
}

// 搜索（功能搜索）
const searchText = ref('')
const recentSearches = ref(JSON.parse(localStorage.getItem('admin_recent_searches') || '[]'))
const saveHistory = (arr) => localStorage.setItem('admin_recent_searches', JSON.stringify(arr.slice(0, 12)))

// 收集 /mall 下的功能页
const allFeatures = computed(() => {
  const routes = router.getRoutes()
  const items = routes
    .filter(r => r.path && r.path.startsWith('/mall'))
    .filter(r => r.path !== '/mall' && r.path !== '/mall/login')
    .map(r => ({
      title: r.meta?.title || r.name || r.path,
      path: r.path
    }))
  // 去重（按 path）
  const seen = new Set()
  return items.filter(it => (seen.has(it.path) ? false : (seen.add(it.path), true)))
})

const searchResults = ref([])

function rankAndFilterFeatures(keyword) {
  const kw = keyword.toLowerCase()
  const score = (it) => {
    const t = (it.title || '').toLowerCase()
    const p = (it.path || '').toLowerCase()
    let s = 0
    if (t.includes(kw)) s += 20
    if (p.includes(kw)) s += 8
    // 提升完全前缀匹配
    if (t.startsWith(kw)) s += 5
    if (p.startsWith(kw)) s += 3
    return s
  }
  return allFeatures.value
    .map(it => ({ ...it, _s: score(it) }))
    .filter(it => it._s > 0)
    .sort((a, b) => b._s - a._s)
}

function doSearch() {
  const kw = (searchText.value || '').trim()
  if (!kw) { searchResults.value = []; return }
  // 存历史
  const arr = [kw, ...recentSearches.value.filter(v => v !== kw)]
  recentSearches.value = arr.slice(0, 12)
  saveHistory(recentSearches.value)
  // 过滤并排序
  searchResults.value = rankAndFilterFeatures(kw)
  // 回车/按钮：若只有一个或想直接跳转，则跳第一个
  if (searchResults.value.length > 0) {
    // 判断是回车触发还是按钮触发不容易，直接不自动跳；若需要自动跳，取消下面注释
    // go(searchResults.value[0].path)
  }
}

function applyKeyword(kw) { searchText.value = kw; doSearch() }
function clearHistory() { recentSearches.value = []; saveHistory([]) }

// 收藏
const FAVORITE_KEY = 'admin_favorites'
const favoriteSet = ref(new Set(JSON.parse(localStorage.getItem(FAVORITE_KEY) || '[]')))
const favoriteGroups = [
  { name: '档案', items: [ { title: '客户', path: '/mall/users' }, { title: '会员', path: '/mall/members' }, { title: '供应商', path: '/mall/suppliers' } ] },
  { name: '采购', items: [ { title: '采购单', path: '/mall/purchase' }, { title: '补货单', path: '/mall/replenishments' }, { title: '退货单', path: '/mall/returns' } ] },
  { name: '门店', items: [ { title: '门店资料', path: '/mall/stores' }, { title: '收银点', path: '/mall/registers' }, { title: '交接班', path: '/mall/shifts' } ] },
  { name: '报表', items: [ { title: '销售分析', path: '/mall/report-sales' }, { title: '款色尺码结构', path: '/mall/report-matrix' }, { title: '库存老化', path: '/mall/report-aging' } ] },
]
const favoriteCount = computed(() => favoriteSet.value.size)
const isFav = (path) => favoriteSet.value.has(path)
const persistFav = () => localStorage.setItem(FAVORITE_KEY, JSON.stringify(Array.from(favoriteSet.value)))
function toggleFav(path) {
  if (favoriteSet.value.has(path)) favoriteSet.value.delete(path)
  else favoriteSet.value.add(path)
  persistFav()
}
function go(path) { router.push(path); closePanel() }

// 档案分组（与档案页一致，便于弹出使用）
const archiveGroups = [
  { name: '系统档案', items: [
    { title: '商品档案', path: '/mall/catalog' },
    { title: '颜色管理', path: '/mall/colors' },
    { title: '尺码管理', path: '/mall/sizes' },
    { title: '吊牌/条码', path: '/mall/tags' },
    { title: '设备与打印', path: '/mall/devices' },
  ]},
  { name: '仓库与库存属性', items: [
    { title: '库存查询', path: '/mall/inventory' },
    { title: '盘点任务', path: '/mall/stocktake' },
    { title: '损益处理', path: '/mall/loss' },
    { title: '调拨单', path: '/mall/transfers' },
    { title: '补货单', path: '/mall/replenishments' },
  ]},
  { name: '供应与采购', items: [
    { title: '供应商', path: '/mall/suppliers' },
    { title: '采购单', path: '/mall/purchase' },
    { title: '退货单', path: '/mall/returns' },
  ]},
  { name: '客户档案', items: [
    { title: '会员中心', path: '/mall/members' },
    { title: '会员等级', path: '/mall/member-tiers' },
    { title: '积分规则', path: '/mall/points' },
    { title: '储值管理', path: '/mall/stored-value' },
  ]},
  { name: '门店与权限', items: [
    { title: '门店资料', path: '/mall/stores' },
    { title: '收银点', path: '/mall/registers' },
    { title: '员工与权限', path: '/mall/users' },
  ]},
  { name: '报表与分析', items: [
    { title: '销售分析', path: '/mall/report-sales' },
    { title: '款色尺码结构', path: '/mall/report-matrix' },
    { title: '季节动销', path: '/mall/report-season' },
    { title: '库存老化', path: '/mall/report-aging' },
    { title: '店员绩效', path: '/mall/report-staff' },
  ]},
]

// 可切换的数据源（默认使用内置 archiveGroups）
import { ref as vueRef } from 'vue'
const archiveGroupsRef = vueRef(archiveGroups)
</script>

<style scoped>
.admin-home { height: 100vh; width: 100vw; background: #f5f7fb; }

/* 左侧竖向导航 */
.left-nav { position: fixed; left: 0; top: 0; bottom: 0; width: 64px; background: #0f172a; color: #cbd5e1; display: flex; flex-direction: column; align-items: center; }
.logo { font-weight: 800; color: #fff; height: 56px; display: flex; align-items: center; justify-content: center; letter-spacing: 1px; }
.nav-items { display: flex; flex-direction: column; gap: 4px; padding: 6px 0; width: 100%; }
.nav-item { width: 100%; height: 44px; background: transparent; border: none; color: #cbd5e1; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 2px; cursor: pointer; }
.nav-item .icon { font-size: 18px; }
.nav-item .label { font-size: 12px; line-height: 1; }
.nav-item:hover { background: rgba(255,255,255,.06); color: #fff; }
.nav-item.active { background: rgba(59,130,246,.18); color: #fff; }

/* 内容 */
.content { margin-left: 64px; height: 100vh; overflow: auto; padding: 12px; }
.toolbar { height: 48px; background: #fff; border-radius: 10px; padding: 0 12px; display: flex; align-items: center; justify-content: space-between; box-shadow: 0 1px 2px rgba(0,0,0,.04); }
.title { font-weight: 700; }
.placeholder { margin-top: 12px; background: #fff; border-radius: 12px; padding: 32px; display: grid; gap: 8px; place-items: center; color: #475569; }
.big { font-size: 20px; font-weight: 700; color: #111827; }
.sub { font-size: 13px; }

/* 抽屉 */
.side-panel { position: fixed; top: 0; left: 64px; height: 100vh; width: 420px; max-width: 92vw; background: #fff; box-shadow: 2px 0 16px rgba(0,0,0,.08); display: flex; flex-direction: column; z-index: 1000; }
.panel-header { height: 56px; display: flex; align-items: center; justify-content: space-between; padding: 0 12px 0 16px; border-bottom: 1px solid #eef1f5; }
.panel-header .title { font-weight: 600; }
.panel-header .muted { color: #6b7280; font-weight: 400; margin-left: 6px; font-size: 12px; }
.close-btn { border: none; background: transparent; font-size: 22px; cursor: pointer; }
.panel-body { padding: 12px; overflow: auto; }
.search-box { display: grid; grid-template-columns: 1fr auto; gap: 8px; }
.section { margin-top: 14px; }
.section-head { display: flex; align-items: center; justify-content: space-between; margin-bottom: 8px; }
.sec-title { font-weight: 600; color: #111827; }
.link { background: transparent; border: none; color: #2563eb; cursor: pointer; }
.tags { display: flex; flex-wrap: wrap; gap: 8px; }
.tag { background: #f3f4f6; padding: 6px 10px; border-radius: 999px; cursor: pointer; font-size: 12px; }
.empty { color: #9ca3af; font-size: 13px; }
.results { display: grid; gap: 8px; }
.result-item { display: flex; align-items: center; justify-content: space-between; background: #f8fafc; border: 1px solid #eef1f5; border-radius: 8px; padding: 10px 12px; cursor: pointer; }
.result-item:hover { background: #f1f5f9; }
.r-main { display: grid; gap: 2px; }
.r-title { font-weight: 600; color: #111827; }
.r-path { font-size: 12px; color: #6b7280; }
.fav-groups { display: grid; grid-template-columns: 1fr 1fr; gap: 10px 16px; }
.group-title { color: #6b7280; font-weight: 600; margin-bottom: 6px; }
.fav-item { display: flex; align-items: center; justify-content: space-between; background: #f8fafc; border: 1px solid #eef1f5; border-radius: 8px; padding: 8px 10px; gap: 8px; }
.fav-name { cursor: pointer; }
.fav-name:hover { color: #2563eb; }
.star-btn { background: transparent; border: none; cursor: pointer; color: #9ca3af; }
.star-btn.on { color: #f59e0b; }

/* 动画 */
.slide-in-enter-active, .slide-in-leave-active { transition: transform .18s ease; }
.slide-in-enter-from, .slide-in-leave-to { transform: translateX(-12px); }
</style>
